<template>
	<view>
		<u-tabbar :beforeSwitch="switchUrl" :inactiveColor="'#8D8D8D'" :activeColor="'#3291F8'" v-model="current"
			:list="list"></u-tabbar>
		<xfTipModal ref="tipModal"></xfTipModal>
	</view>
</template>

<script>
	export default {
		name: "userTabbar",
		data() {
			return {
				list: [{
						iconPath: "/static/image/tabbar/home.png",
						selectedIconPath: "/static/image/tabbar/homeSel.png",
						text: '首页',
						customIcon: true,
						pagePath: "/pages/userPage/home/index"
					},
					{
						iconPath: "/static/image/tabbar/work.png",
						selectedIconPath: "/static/image/tabbar/workSel.png",
						text: '灵工',
						customIcon: true,
						pagePath: "/pages/userPage/job/index"
					},

					{
						iconPath: "/static/image/tabbar/chat.png",
						selectedIconPath: "/static/image/tabbar/chatSel.png",
						text: '消息',
						customIcon: true,
						count: '',
						pagePath: "/pages/chat/index"
					},
					{
						iconPath: "/static/image/tabbar/user.png",
						selectedIconPath: "/static/image/tabbar/userSel.png",
						text: '我的',
						customIcon: true,
						pagePath: "/pages/userPage/my/index"
					},
				],
				current: 0
			}
		},
		computed: {
			unreadCount() {
				let count = 0;
				this.chatStore.chats.forEach(chat => {
					if (!chat.delete) {
						count += chat.unreadCount;
					}
				})
				return count;
			},
			readSum(){
				return this.chatStore.readSum
			},
		},
		watch: {
			unreadCount(newCount, oldCount) {
				this.refreshUnreadBadge();
			},
			readSum(newCount, oldCount){
				this.refreshUnreadBadge()
			}
		},
		mounted() {
			if (uni.getStorageSync('token')) {
				this.refreshUnreadBadge()
			}
		},
		methods: {
			async refreshUnreadBadge() {
				let data = await this.chatStore.sysNoRead()
				if (this.unreadCount > 0) {
					this.list[2].count = this.unreadCount + data.num;
				} else {
					let count = data.num > 0 ? data.num : ''
					this.list[2].count = '' + count
				}
			},
			switchUrl(index) {
				if (index == 2 || index == 3) {
					if (this.xf.isLogin()) {
						return true
					} else {
						this.$refs.tipModal.open({
							content: "您还未登录,请先登录",
							btnText: "去登录",
							showCancel: true,
							success: function() {
								uni.navigateTo({
									url: "/pages/login/login"
								})
							}
						})
					}
				} else {
					return true
				}
			}
		}
	}
</script>